/* 
 * plugin pour l'upload de fichier dans jQuery
 */
(function($) {
    $.fn.sfUploader = function(parametres) {
        var defauts = {
            url: 'uploader.php',
            path: 'uploads'
        };
        var params = $.extend(defauts, parametres);
        var i = 1;
        
        return this.each(function() {
            var $this = $(this);
            var $parent = $this.parent();
            var id = $this.attr('id');
            // Nommage
            var formId = 'form_' + i;
            // Insertion d'un formulaire invisible
            $parent.append("<form id='" + formId + "' action='" + params.url + " 'method='post' enctype='multipart/form-data' class='upload-hide'></form>");
            $parent.find('#' + formId).append("<input type='file' name='myfile' class='upload-file'>");
            //$parent.find('#' + formId).append("<div class='progress'><div class='bar'></div><div class='percent'></div></div>");
            // Ajout d'un verrou
            $this.attr('data-lock', 1);
            i++;
            // Upload
            options = {
                beforeSend: function() {
                    //$('#' + formId + ' .progress .bar').width('0%');
                    //$('#' + formId + ' .progress .percent').html('0%');
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    //$('#' + formId + ' .progress .bar').width(percentComplete + '%');
                    //$('#' + formId + ' .progress .percent').html(percentComplete + '%');
                },
                success: function() {
                    //$('#' + formId + ' .progress .bar').width('100%');
                    //$('#' + formId + ' .progress .percent').html('100%');
                },
                complete: function(response) {
                    $this.val(response.responseText);
                },
                error: function() {
                    alert("Le fichier n'a pas été téléchargé!!!");
                }
            };
            // Events
            $('#' + formId).ajaxForm(options);
            $('#' + formId + ' .upload-file').change(function(e){
                $('#' + formId).submit();
            });
            $this.click(function(e){
                e.preventDefault();
                var lock = parseInt($this.attr('data-lock'));
                //alert(lock);
                if(lock === 1){
                    //window.location.href = params.path + '/' + $this.val();
                    window.open(params.path + '/' + $this.val());
                }else{
                    $('#' + formId + ' .upload-file').click();
                }
            });
        });
    };
})(jQuery);


